<?php
/*
Plugin Name: 最新文章签名
Plugin URI: http://wanwp.com/plugins/latest-post-signatrue/
Description: 生成显示最新文章标题的图片
Author: 冰古
Version: 1.0
Author URI: http://bingu.net
License: GNU General Public License 2.0 http://www.gnu.org/licenses/gpl.html
*/

$lpsFont = 'msyh.ttf'; // 字体。
$lpsPath = ABSPATH.'/wp-content/plugins/latest-post-signature/'; // lps路径
$lpsImgPath = $lpsPath.'img/'; //图片路径
$lpsSavedImgPath = ABSPATH; // 把生成的图片放到wordpress安装的根目录下。

function getLatestPost(){
    global $wpdb, $tableposts;

    // 取得最新发布的文章的标题
    $sql = "SELECT `post_title`, `post_date_gmt` FROM {$tableposts}
            WHERE post_status = 'publish'
            ORDER BY  `post_date_gmt` DESC
            LIMIT 0, 1";
    $posts = $wpdb->get_results($sql);

    foreach ($posts as $post) {
        $post_title = stripslashes($post->post_title);
        $post_date = $post->post_date_gmt;
        writePng($post_title,$post_date);
    }
}

function writePng($title, $date){
    global $lpsFont, $lpsPath, $lpsSavedImgPath, $lpsImgPath;

    // 参数先整好
    $date = date("发表于Y-m-d", strtotime($date)+28800);
    $save = $lpsSavedImgPath.'lps.png';
    $font = $lpsPath . $lpsFont;

    $gfx = imagecreatefrompng($lpsImgPath.'lps.png');

    $color = imagecolorallocate($gfx, 0, 0, 0); // 文字颜色，黑色
    imagettftext($gfx,
                 12,
                 0,
                 8,
                 28,
                 $color,
                 $font,
                 $title);
    imagettftext($gfx,
                 10,
                 0,
                 238,
                 50,
                 $color,
                 $font,
                 $date);
             
   imagepng($gfx, $save); 
}

add_action('publish_post', 'getLatestPost');
register_activation_hook( __FILE__, 'getLatestPost' );